package com.fengye.algorithms.leecode;

/**
 * @Author fengye
 * @Date 2023/4/21 6:08
 **/
public class findFirstAndLastPositionOfElementInSortedArray34 {

    public static void main(String[] args) {
        new findFirstAndLastPositionOfElementInSortedArray34().searchRange(new int[]{1,4}, 4);
    }
    public int[] searchRange(int[] nums, int target) {
        int[] result = new int[]{-1,-1};
        if(nums == null || nums.length == 0) {
            return result;
        }
        int len = nums.length;
        if(nums[0] > target || nums[len-1] < target) {
            return result;
        }

        int left = 0;
        int right = len - 1;
        while (left <= right) {
            int mid = left + ((right-left)>>1);
            // 这里要最后left==right的情况再判断一次
            if(nums[mid] == target || left==right) {
                for(int i = mid;i>=0;i--) {
                    if(nums[i] == target) {
                        result[0] = i;
                    } else {
                        break;
                    }
                }
                for(int i = mid;i<len;i++) {
                    if(nums[i] == target) {
                        result[1] = i;
                    } else {
                        break;
                    }
                }
                break;
            } else if(nums[mid] < target){
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }

        return result;
    }
}
